package org.example.back.service.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class EmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String emailFrom;   // 从配置文件取发件方

    // 存储验证码与有效期（邮箱 -> [验证码, 过期时间]）
    private final ConcurrentHashMap<String, VerificationCodeData> verificationCodeStore = new ConcurrentHashMap<>();

    private static final int CODE_VALIDITY_MINUTES = 5; // 验证码有效期5分钟

    /**
     * 发送验证码邮件
     *
     * @param to 接收邮箱
     * @return 返回生成的验证码
     */
    public String sendVerificationCode(String to) {
        // 生成随机验证码
        String verificationCode = generateVerificationCode();

        // 固定主题和内容
        String subject = "健康生活助手【用户注册】验证码";
        String text = "您的验证码是：" + verificationCode + "，有效期5分钟，请勿泄露。";

        // 创建邮件消息对象
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(emailFrom);
        System.out.println(to);
        message.setTo(to);

        message.setSubject(subject);
        message.setText(text);

        try {
            // 发送邮件
            mailSender.send(message);

            // 保存验证码到存储（设置有效期）
            LocalDateTime expiryTime = LocalDateTime.now().plusMinutes(CODE_VALIDITY_MINUTES);
            verificationCodeStore.put(to, new VerificationCodeData(verificationCode, expiryTime));

        } catch (Exception e) {
            System.err.println("邮件发送失败：" + e.getMessage());
            throw new RuntimeException("邮件发送失败，请稍后重试");
        }

        return verificationCode;
    }

    /**
     * 验证用户输入的验证码是否正确
     *
     * @param email 邮箱地址
     * @param inputCode 用户输入的验证码
     * @return 验证结果：true 表示验证通过，false 表示失败
     */
    public boolean verifyCode(String email, String inputCode) {
        VerificationCodeData codeData = verificationCodeStore.get(email);

        // 验证码不存在或已过期
        if (codeData == null || codeData.getExpiryTime().isBefore(LocalDateTime.now())) {
            verificationCodeStore.remove(email); // 清理过期数据
            return false;
        }

        // 验证码匹配
        boolean isValid = codeData.getCode().equals(inputCode);

        // 如果验证通过，删除存储的验证码（一次性验证码）
        if (isValid) {
            verificationCodeStore.remove(email);
        }

        return isValid;
    }

    /**
     * 工具方法：生成6位随机验证码
     *
     * @return 随机6位数字验证码
     */
    private String generateVerificationCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10)); // 生成0-9的随机数
        }
        return code.toString();
    }

    /**
     * 内部类：存储验证码和有效期
     */
    private static class VerificationCodeData {
        private final String code;
        private final LocalDateTime expiryTime;

        public VerificationCodeData(String code, LocalDateTime expiryTime) {
            this.code = code;
            this.expiryTime = expiryTime;
        }

        public String getCode() {
            return code;
        }

        public LocalDateTime getExpiryTime() {
            return expiryTime;
        }
    }
}
